const {
	xm_uuid,
	xm_appKey
} = require('@/app.config.js');
(function() {
	const isObject = function(obj) {
		if (obj === undefined || obj === null) {
			return false;
		} else {
			return toString.call(obj) == "[object Object]";
		}
	};
	// 劫持Component
	const _componentProto_ = Component;
	Component = function(options) {
		// options.methods内有uniapp注入的事件处理器__e及mpHook
		Object.keys(options.methods).forEach(methodName => {
			if (methodName == "__e") {
				// 劫持事件处理器
				eventProxy(options.methods, methodName);
			}
		});
		_componentProto_.apply(this, arguments);
	};

	function eventProxy(methodList, methodName) {
		const _funcProto_ = methodList[methodName];
		methodList[methodName] = function() {
			_funcProto_.apply(this, arguments);
			let prop = {};
			if (isObject(arguments[0])) {
				if (Object.keys(arguments[0]).length > 0) {
					// 记录触发页面信息
					const pages = getCurrentPages();
					const currentPage = pages[pages.length - 1];
					prop["$page_path"] = currentPage.route; // 页面路径
					prop["$page_query"] = currentPage.options || {}; // 页面携带的query参数
					const type = arguments[0]["type"];
					const current_target = arguments[0].currentTarget || {};
					const dataset = current_target.dataset || {};
					prop["$event_type"] = type;
					prop["$event_timestamp"] = Math.floor(Date.now() / 1000);
					prop["$element_id"] = current_target.id;
					const eventDetail = arguments[0].detail;
					prop["$event_detail"] = eventDetail;
					prop["$data_set"] = dataset;

					if (!!dataset.eventOpts && type) {
						if (type == "tap") {
							// 只记录点击事件
							const event_opts = dataset.eventOpts;
							if (Array.isArray(event_opts) && event_opts[0].length === 2) {
								let eventFunc = [];
								event_opts[0][1].forEach(event => {
									eventFunc.push({
										name: event[0],
										params: event[1] || ""
									});
								});
								prop["$event_function"] = eventFunc;
							}
						}
						postWeData(prop); // 在此处上传记录的事件数据
					}
				}
			}
		};
	}
	const postWeData = function(event) {
		let el = uni.getStorageSync('tabEvent') || [];
		if (event.$data_set.code || event.$data_set.eventname) {
			delete event.$data_set.eventOpts
			let obj = event.$data_set;
			obj.t = event.$event_timestamp.toString();
			console.log(obj, '埋点');
			// obj= {
			// 	code: event.$data_set.code,
			// 	eventName: event.$data_set.eventname,
			// 	t: event.$event_timestamp
			// };
			el.push(obj);
			uni.setStorageSync('tabEvent', el);
		}
	};
})();
